import { world } from "@minecraft/server";
import { GameComponent } from "@sapi-game/main";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { BuildWereWolfPlayerName } from "../func";
import { WereWolfVotePhase } from "../phases/vote";

export class WereWolfAttackVoteComponent extends GameComponent<WereWolfVotePhase> {
    voteCount: number = 0;

    override onAttach(): void {
        this.reset();
        this.subscribe(world.afterEvents.entityHitEntity, (e) => {
            if (
                e.damagingEntity.typeId != EntityTypeIds.Player ||
                e.hitEntity.typeId != EntityTypeIds.Player
            )
                return;

            const voter = this.context.players.getById(e.damagingEntity.id);
            const votee = this.context.players.getById(e.hitEntity.id);
            if (!voter || !votee) return;
            if (voter.voted) {
                voter.sendMessage("§c你已经投过票了");
                return;
            }
            if (voter.dead) {
                voter.sendMessage("§c你已经死亡，无法投票");
                return;
            }
            if (votee.dead) {
                voter.sendMessage("§c该玩家已死亡，无法被投票");
                return;
            }
            if (voter.id === votee.id) {
                voter.sendMessage("§c你不能投自己");
                return;
            }

            votee.votes++;
            voter.voted = true;
            //更新票数
            if (votee.player) this.state.voteDb.set(votee.player, votee.votes);
            this.voteCount++;
            this.context.players.sendMessage(
                `${BuildWereWolfPlayerName(
                    voter
                )} §b将票投给了 ${BuildWereWolfPlayerName(
                    votee
                )}\n§e当前参与投票人数:§a${this.voteCount}§f/§c${
                    this.context.players.filter((p) => !p.dead).length
                }`
            );
        });
    }

    reset() {
        this.context.players.forEach((p) => {
            p.voted = false;
            p.votes = 0;
        });
    }
}
